package vip.xiaozhao.paotui.controller.detail;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import vip.xiaozhao.paotui.controller.BaseController;
import vip.xiaozhao.paotui.intf.dto.ResponseDO;
import vip.xiaozhao.paotui.intf.entity.PaotuiDetail;
import vip.xiaozhao.paotui.intf.enums.PaotuiTypeEnum;
import vip.xiaozhao.paotui.intf.service.PaotuiDetailService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;

@RestController
@RequestMapping("/detail/publish")
@Slf4j
public class PaotuiPublishController extends BaseController {


    @Resource
    private PaotuiDetailService paotuiDetailService;

    @RequestMapping("/insert")
    public ResponseDO insert(PaotuiDetail detail , HttpServletRequest request, HttpServletResponse response) {
        log.info("publish detail , detail =: "  + detail);

        //1 校验参数
        String ret = verifyParams(detail);
        if(!StringUtils.equals(ret,SUCCESS) ){
            return ResponseDO.fail(ret);
        }
        //2 用户需要登录
        int currentUserId = getCurrentUserId(request);
        if (currentUserId == 0) {
            log.info("user does not login in");
            return ResponseDO.fail(NOT_LOGIN);
        }
        //3 insert 部分逻辑的计算
        //自动计算金额，具体方案见产品，这里不展开
        BigDecimal amount = new BigDecimal("30");
        detail.setAmount(amount);

        paotuiDetailService.insert(detail);

        return ResponseDO.success(detail.getId());
    }

    private  String verifyParams(PaotuiDetail detail){
        if(detail == null){
            return "参数不正确";
        }
        PaotuiTypeEnum typeEnum = PaotuiTypeEnum.getById(detail.getGoodsType());
        if(typeEnum == null){
            return "物品种类不正确";
        }
        //其它枚举和时间规则校验，此处省略
        if(!StringUtils.isNotBlank(detail.getRemark()) && detail.getRemark().length() > 150){
            return "备注长度超过150个字";
        }

        //4 需用对备注 进行非法字符的过滤，使用腾讯小程序的非法字符接口，这里涉及到账号省略。

        return SUCCESS;

    }

}
